from sqlalchemy import Column, Integer, String, DateTime, SmallInteger, BigInteger
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declared_attr
from src.common.db.database import Base
from src.common.utils.snowflake import generate_id
from typing import Dict, Any
from datetime import datetime

class BaseModel(Base):
    """基础模型类"""
    __abstract__ = True
    
    # 主键 - 使用雪花算法生成
    id = Column(BigInteger, primary_key=True, default=generate_id, comment='主键ID（雪花算法生成）')
    
    # 审计字段
    create_user = Column(Integer, comment='创建用户')
    create_time = Column(DateTime, default=func.now(), comment='创建时间')
    update_user = Column(Integer, comment='更新用户')
    update_time = Column(DateTime, default=func.now(), onupdate=func.now(), comment='更新时间')
    
    # 状态字段
    status = Column(SmallInteger, default=1, comment='状态：0-删除，1-正常')
    
    # 租户字段
    tenant_id = Column(String(50), comment='租户ID')
    
    @declared_attr
    def __tablename__(cls):
        """自动生成表名"""
        return cls.__name__.lower()
    
    def to_dict(self, exclude_fields: list = None) -> Dict[str, Any]:
        """转换为字典
        
        Args:
            exclude_fields: 需要排除的字段列表
        
        Returns:
            字典格式的模型数据
        """
        exclude_fields = exclude_fields or []
        result = {}
        
        for column in self.__table__.columns:
            field_name = column.name
            if field_name in exclude_fields:
                continue
                
            value = getattr(self, field_name)
            
            # 处理日期时间字段
            if isinstance(value, datetime):
                result[field_name] = value.isoformat()
            else:
                result[field_name] = value
                
        return result
    
    def update_from_dict(self, data: Dict[str, Any], exclude_fields: list = None):
        """从字典更新模型数据
        
        Args:
            data: 要更新的数据字典
            exclude_fields: 需要排除的字段列表
        """
        exclude_fields = exclude_fields or ['id', 'create_time', 'create_user']
        
        for key, value in data.items():
            if key in exclude_fields:
                continue
                
            if hasattr(self, key):
                setattr(self, key, value)
    
    @classmethod
    def get_table_name(cls) -> str:
        """获取表名"""
        return cls.__tablename__
    
    def __repr__(self):
        """字符串表示"""
        return f"<{self.__class__.__name__}(id={self.id})>"
    
    def is_active(self) -> bool:
        """检查记录是否为活跃状态"""
        return self.status == 1
    
    def soft_delete(self, user_id: int = None):
        """软删除"""
        self.status = 0
        if user_id:
            self.update_user = int(user_id)
    
    def restore(self, user_id: int = None):
        """恢复删除"""
        self.status = 1
        if user_id:
            self.update_user = int(user_id)